from django.views import View
from django import http
from django.shortcuts import render
from django_redis import get_redis_connection

import json, base64, pickle
from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE


class CartsView(View):
    """购物车管理"""

    def post(self, request):
        """添加购物车"""
        # 接受请求体数据
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 校验参数是否齐全
        if all([sku_id, count]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        try:
            # 判断sku_id是否存在
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku_id不存在')

        try:
            # 判断count是否为数字
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count参数错误')

        if isinstance(selected, bool) is False:
            return http.HttpResponseForbidden('参数有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 登入用户存储购物车数据到redis
            # 创建redis数据库
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 调用hincrby() 要添加的商品不存在就是新增,和如果要添加的商品已经存在就会对value做增量
            pl.hincrby('carts_%s' % user.id, sku_id, count)
            # 如果当前商品是勾选把当前sku_id添加到set集合 sadd
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            pl.execute()
            # 响应
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})

        else:
            # 未登录用户,操作cookie购物车
            cart_str = request.COOKIES.get('carts')
            # 判断cookie中是否有购物车数据
            if cart_str:
                # 如果取到了cookie购物车数据,将字符串转回字典
                cart_str_bytes = cart_str.encode()
                cart_bytes = base64.b64decode(cart_str_bytes)
                cart_dict = pickle.loads(cart_bytes)

                # 判断当前要添加到商品是否已经添加过,如果添加过,对count做增量
                if sku_id in cart_dict:
                    # 取出已经添加过的商品原有要购物车数量
                    origin_count = cart_dict[sku_id]['count']
                    count += origin_count

            else:
                # 如果没有cookie购物车数据,准备一个大字典
                cart_dict = {}
            # 如果本次添加的是一个新商品,就增加到大字典
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 将购物车大字典,在转回到字符串
            cart_bytes = pickle.dumps(cart_dict)
            cart_str_bytes = base64.b64encode(cart_bytes)
            cart_str = cart_str_bytes.decode()
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            response.set_cookie('carts', cart_str)
            return response

    def get(self, request):
        """购物车数据展示"""
        user = request.user
        if user.is_authenticated:
            # 登录用户, 查询redis购物车
            redis_conn = get_redis_connection('carts')
            # 获取redis中的购物车数据
            redis_cart  = redis_conn.hgetall('carts_%s' % user.id)
            # 获取redis中的选中状态
            cart_selected = redis_conn.smembers('selected_%s' % user.id)

            """
                {
                    sku_id_1: {'count': 1, 'selected': True},
                    sku_id_2: {'count': 2, 'selected': False},

                }
            """
            # 将redis中的数据结构成cookie中的格式一致,方便同意查询
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            # 未登录用户,查询cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转成bytes类型,在将bytes转成base64的bytes,最后将bytes转成字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                # 如果当前没有购物车数据,直接显示购物车
                return render(request, 'cart.html')

        # 构造购物车渲染数据
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': str(cart_dict.get(sku.id).get('selected')),
                'default_image': sku.default_image.url,
                'price': str(sku.price),
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
            })
        context = {
            'cart_skus': cart_skus,
        }

        # 渲染购物车页面
        return render(request, 'cart.html', context)

    def put(self, request):
        """修改购物车"""
        # 接收body参数请求体
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if all([sku_id, count]) is False:
            return http.HttpResponseForbidden('缺少必传参数')
        try:
            # 判断sku_id是否存在
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku_id不存在')
        try:
            # 判断count是否为数字
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')

        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登入
        user = request.user
        # 创建响应对象
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image': sku.default_image.url,
            'price': str(sku.price),
            'amount': str(sku.price * count),
        }
        # 创建响应对象
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        if user.is_authenticated:
            # 登录用户,修改redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 因为借口设计为幂等的,直接覆盖
            pl.hset('carts_%s' % user.id, sku_id, count)
            # 是否选中
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

        else:
            # 用户未登入,修改cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': 'cookie数据没有获取到'})

            # 直接新数据覆盖cookie大字典旧数据
            cart_dict[sku.id] = {
                'count': count,
                'selected': selected,
            }
            # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response.set_cookie('carts', cookie_cart_str)
        return response

    def delete(self, request):
        """删除购物车"""
        # 接收sku_id参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 校验sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku_id不存在')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户登录,操作redis购物车数据
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 删除建,就等于删除整条记录
            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()
            # 响应数据
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除商品成功'})
        else:
            # 用户未登录, 操作cookie购物车数据
            # 先获取cookie购物车数据
            cart_str = request.COOKIES.get('carts')
            # 判断是否获取到cookie购物车数据
            if cart_str:
                # 获取到之后字符串转换成字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                # 没有获取到提前响应
                return http.HttpResponseForbidden('缺少cookie')
            # 把当前sku_id对就的键值对从cart_dict删除
            if sku_id in cart_dict:
                del cart_dict[sku_id]  # 判断当前要删除的商品存在时,再去删除
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})

            # 判断当前字典是否为空,如果为空将cookie删除
            if not cart_dict:
                # 直接把cookie中的购物车数据删除
                response.delete_cookie('carts')
                return response

            # 字典转字符串
            cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response.set_cookie('carts', cart_str)
            return response


class CartsSelectAllView(View):
    """全选购物车"""
    def put(self, request):
        # 接收body请求体参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('selected参数不足')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 登入用户,操作redis购物车数据,创建redis连接
            redis_conn = get_redis_connection('carts')
            # 获取hash字典数据
            cart = redis_conn.hgetall('carts_%s' % user.id)
            sku_id_list = cart.keys()
            # 如果是全选,把hash中的所有sku_id添加到set集合中
            if selected:
                redis_conn.sadd('selected_%s' % user.id, *sku_id_list)

            # 如果是取消全选,直接移除redis的set集合
            else:
                redis_conn.delete('selected_%s' % user.id)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

        else:
            # 用户未登录, 操作cookie, 获取cookie购物车数据
            cart_str = request.COOKIES.get('carts')
            # 判断是否获取cookie
            if cart_str:
                # 如果获取到吧字符串转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                # 如果没有获取到cookie数据, 提前响应
                return http.HttpResponseForbidden('cookie没有获取到')

            # 遍历cookie字典将里面的selected全部改为前端传入的状态
            for sku_id in cart_dict:
                cart_dict[sku_id]['selected'] = selected

            # 把字典转回字符串
            cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 设置cookie
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
            response.set_cookie('carts', cart_str)
            return response


class CartsSimpleView(View):
    """mini版购物车展示"""
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            # 登录用户,查询redis购物车数据
            redis_conn = get_redis_connection('carts')
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # 取出所有redis数据库里set成分  smembers(成分)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)
            # 将redis中的两个数据统一格式,跟cookie中的格式一致,方便统一查询
            cart_dict = {}
            for sku_id_bytes in redis_cart:
                cart_dict[int(sku_id_bytes)] = {
                    'count': int(redis_cart[sku_id_bytes]),
                    'selected': sku_id_bytes in cart_selected
                }
        else:
            # 用户未登录
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '没有数据', 'cart_skus': []})

        # 构造简单购物车json数据
        cart_skus = []  # 包装前端需要渲染的购物车商品所有数据
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'count': cart_dict[sku.id]['count'],
            })

        # 响应json列表数据
        return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '没有数据', 'cart_skus': cart_skus})


"""

"""